﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Editor.WinForm;
using WeifenLuo.WinFormsUI.Docking;
using Editor.Sprite2DEditor;
using CasaEngineWrapper;
using CasaEngineEditor.Log;
using Editor.Sprite2DEditor.SpriteSheetPacker.sspack;

namespace Editor
{
    public partial class ContentBrowserForm 
        : DockContent
    {
        
        //private ContentBrowser m_ContentBrowser;
        private BackgroundWorker m_BackgroundWorker;
        private int m_Percent, m_PercentTotal;
        
        /// <summary>
        /// 
        /// </summary>
        public ContentBrowserForm()
        {
            InitializeComponent();

            /*m_ContentBrowser = new ContentBrowser();
            m_ContentBrowser.Refresh();
            RefreshPackage();*/
        }
        /*
        /// <summary>
        /// 
        /// </summary>
        public void RefreshPackage()
        {
            treeView1.Nodes.Clear();

            foreach (Package p in m_ContentBrowser.Packages)
            {
                TreeNode n = GetNodeFromPath(p.PathFromProjectPath);
                TreeNode node = new TreeNode(p.Name);

                if (n == null)
                {
                    treeView1.Nodes.Add(node);
                }
                else
                {
                    n.Nodes.Add(node);
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void RefreshItem()
        {
            
        }

        #region TreeView

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path_"></param>
        /// <returns></returns>
        TreeNode GetNodeFromPath(string path_)
        {
            TreeNode ret = null;

            string[] dirs = path_.Split(Path.PathSeparator);

            foreach (string dir in dirs)
            {
                if (string.IsNullOrWhiteSpace(dir) == false)
                {
                    TreeNode node = FindOrCreateNode(dir, null);
                }
            }

            return ret;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dir_"></param>
        /// <param name="node_"></param>
        /// <returns></returns>
        TreeNode FindOrCreateNode(string dir_, TreeNode node_)
        {
            TreeNodeCollection collect;

            if (node_ == null)
            {
                collect = treeView1.Nodes;
            }
            else
            {
                collect = node_.Nodes;
            }

            foreach (TreeNode n in treeView1.Nodes)
            {
                if (n.Text.Equals(dir_) == true)
                {
                    return n;
                }
            }

            TreeNode nd = new TreeNode(dir_);
            collect.Add(nd);
            return nd;
        }*/

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            //GetItemFromPackage()
        }
        /*
        #endregion

        #region ContextMenuStrip
        */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addAnimSetToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addAnimTreeToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addSoundToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newSpritesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddSpriteAndAnimForm form = new AddSpriteAndAnimForm();

            if (form.ShowDialog(this) == DialogResult.OK)
            {
                AddSprites(form.PackageName, form.Files, form.DetectAnimation2D);
            }
        }
        
        #region AddSprite

        /// <summary>
        /// 
        /// </summary>
        /// <param name="packageName_"></param>
        /// <param name="files_"></param>
        /// <param name="detectAnimation2D_"></param>
        public void AddSprites(string packageName_, string[] files_, bool detectAnimation2D_)
        {
            object[] args = new object[3] {packageName_, files_, detectAnimation2D_};
            BgWorkerForm form = new BgWorkerForm(GenerateSprites, args);
            form.Text = "Build sprite sheet";
            form.ShowDialog(this);
            form.Dispose();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GenerateSprites(object sender, DoWorkEventArgs e)
        {
            m_BackgroundWorker = sender as BackgroundWorker;
            object[] args = e.Argument as object[];

            string packageName = args[0] as string;
            string[] files = args[1] as string[];
            bool detectAnimation2D = (bool) args[2];

            m_PercentTotal = files.Length;
            m_Percent = 0;

            //Package package = GameInfo.Instance.PackageManager.CreateOrGetPackage(packageName);

            //crop image and copy image in memory
            foreach (string name in files)
            {
                //OnProgressChanged("Analysing... " + Path.GetFileName(name));

                string sprite2DFileName = GameInfo.Instance.Project.ProjectPath + Path.DirectorySeparatorChar + "Temp";
                //sprite2DFileName += GameInfo.Instance.ProjectManager.ImageDirPath + Path.DirectorySeparatorChar + Path.GetFileName(name);

                System.Drawing.Rectangle rect;
                System.Drawing.Point point;
                Bitmap bitmap = new Bitmap(name);

                if (ImagePacker.ShrinkBitmap(bitmap, out rect, out point) == true)
                {
                    //package.AddSprite();


                    /*
                    Sprite2D sprite2D = new Sprite2D(null, sprite2DFileName);
                    sprite2D.AssetFileName = Path.GetFileName(name);
                    sprite2D.Name = Path.GetFileNameWithoutExtension(name);
                    sprite2D.HotSpot = new Microsoft.Xna.Framework.Point(point.X, point.Y);
                    sprite2D.PositionInTexture = new Microsoft.Xna.Framework.Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
                    */
                    /*ShapePolygone poly = new ShapePolygone(
                        new ShapePolygone(
                            new Vector2(0, 0),
                            new Vector2(sprite2D.PositionInTexture.Width, 0),
                            new Vector2(sprite2D.PositionInTexture.Width / 2, sprite2D.PositionInTexture.Height)));
                    poly.Points.Add(Vector2.UnitX * sprite2D.PositionInTexture.Width);
                    sprite2D.AddCollision(poly);*/
                    //GameInfo.Instance.Asset2DManager.AddSprite2D(sprite2D); //@TODO insert into package
                }
                else
                {
                    LogManager.Instance.WriteLineError("AddSprites() : can't analyzed the image : '" + name + "'");
                    bitmap.Dispose();
                    continue;
                }

                /*bitmap.Save(sprite2DFileName);
                bitmap.Dispose();*/
            }

            m_BackgroundWorker = null;
        }
        /*
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void BuildSpriteSheet(object sender, DoWorkEventArgs e)
        //{
        //    m_BackgroundWorker = sender as BackgroundWorker;

        //    string mapFileName, spriteSheetFileName;
        //    SpriteSheetTask.SpriteSheetBuild build = (SpriteSheetTask.SpriteSheetBuild)e.Argument;

        //    Builder builder = new Builder();
        //    builder.ProgressChanged += new EventHandler<ProgressChangedEventArgs>(builder_ProgressChanged);
        //    int res = builder.Build(build, out spriteSheetFileName, out mapFileName);

        //    if (res == 0)
        //    {
        //        if (m_OnSpriteSheetBuildFinished != null)
        //        {
        //            BuildResultEventArgs eventArgs = new BuildResultEventArgs(spriteSheetFileName, mapFileName, build.DetectAnimations);
        //            m_OnSpriteSheetBuildFinished.Invoke(this, eventArgs);
        //        }

        //        try
        //        {
        //            File.Delete(mapFileName);
        //            File.Delete(spriteSheetFileName);
        //        }
        //        catch (Exception ex)
        //        {
        //            LogManager.Instance.WriteException(ex);
        //            MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //        }
        //    }
        //    else
        //    {
        //        string msg = "Error packing images: " + Builder.ErrorCodeToString((FailCode)res);//SpaceErrorCode((sspack.FailCode)res);
        //        LogManager.Instance.WriteLineError(msg);
        //        MessageBox.Show(null, msg, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        //    }

        //    m_BackgroundWorker = null;
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnProgressChanged(string txt_)
        {
            LogManager.Instance.WriteLineDebug(txt_);
            SetProgress(1, "Packing image...\n" + txt_);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="percent_"></param>
        /// <param name="msg_"></param>
        private void SetProgress(int percent_, string msg_ = null)
        {
            m_Percent += percent_;

            if (m_BackgroundWorker != null)
            {
                m_BackgroundWorker.ReportProgress(
                    (int)((float)m_Percent / (float)m_PercentTotal * 100.0f),
                    msg_);
            }
        }

        #endregion

        #endregion

        #region Tags
        */
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonShowTag_Click(object sender, EventArgs e)
        {
            splitContainer1.Panel2Collapsed = !splitContainer1.Panel2Collapsed;

            if (splitContainer1.Panel2Collapsed == true)
            {
                this.buttonShowTag.Text = "◄";
            }
            else
            {
                this.buttonShowTag.Text = "►";
            }
        }
        
        #endregion
        
    }
}
